'use strict';
var BaseController = require('./base.js');

class LoginController extends BaseController {
    async login() {
        const username = this.ctx.request.body.username;
        const password = await this.service.tools.md5(this.ctx.request.body.password);
        const code = this.ctx.request.body.code.replace(/\s+/g,"");
        if (this.ctx.session.code) {
            if (code.toUpperCase() == this.ctx.session.code.toUpperCase()) {
                const result = await this.ctx.model.Admin.findOne({"username": username, "password": password});
                if (result) {
                    const {is_super,_id,username,mobile,email,role_id} = result;
                    const data = {
                        is_super,_id,username,mobile,email,role_id
                    }
                    this.ctx.session.userinfo = data;
                    // this.ctx.session.code = '';
                    this.success(200, '登录成功', data)
                } else {
                    this.error(303, '用户名或者密码不对');
                }
            } else {
                this.error(303, '验证码错误');
            }
        } else {
            this.error(303, '验证码过期，请再次请求验证码');
        }
    }

    async verify() {
        var captcha = await this.service.tools.captcha();  //服务里面的方法
        this.ctx.response.type = 'image/svg+xml';
        this.ctx.body = captcha.data;
    }

    async loginOut() {
        this.ctx.session.userinfo = null;
        this.success(200,"退出登录成功")
    }
}

module.exports = LoginController;
